// Copyright 2013 Petar Maymounkov
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package ns

import (
	"io"
	"os"
	"reflect"
	"strconv"
	"sync"
	"unicode"

	"circuit/kit/lang"
)

func uid() string {
	return strconv.Itoa(os.Getuid())
}

func gid() string {
	return strconv.Itoa(os.Getgid())
}

func valueHash(recv reflect.Value) uint64 {
	return uint64(lang.ComputeReceiverID(recv.Interface()))
}

func interfaceHash(recv interface{}) uint64 {
	return valueHash(reflect.ValueOf(recv))
}

func filename(n string) string {
	var m = []byte(n)
	m[0] = byte(unicode.ToLower(rune(m[0])))
	return string(m)
}

func min(x, y int) int {
	if x < y {
		return x
	}
	return y
}

//
type syncReader struct {
	sync.Mutex
	io.Reader
}

func (x *syncReader) Read(p []byte) (int, error) {
	x.Lock()
	defer x.Unlock()
	return x.Reader.Read(p)
}

//
type syncWriter struct {
	sync.Mutex
	io.Writer
}

func (x *syncWriter) Write(p []byte) (int, error) {
	x.Lock()
	defer x.Unlock()
	return x.Writer.Write(p)
}

//
type readWriteCloser struct {
	io.ReadCloser
	io.WriteCloser
}

func (rwc *readWriteCloser) Close() error {
	rwc.ReadCloser.Close()
	rwc.WriteCloser.Close()
	return nil
}
